import { TaskQueueTool } from "../Utils/TaskQueueTool"

const { ccclass, property } = cc._decorator;

let ItemNum = 51,
    BaseJumpTime = 1,
    Jump = `Jump`

// 音频跳动组件
@ccclass
export class Main extends cc.Component {

    @property(cc.Node)
    ndCtn: cc.Node = null
    @property(cc.Node)
    ndItem: cc.Node = null
    TaskQueueTool: TaskQueueTool;
    _oHeight: number;
    _itemHeights: number[];

    onLoad() {
        cc.log(`${cc.js.getClassName(this)} onLoad`)

        this.TaskQueueTool = new TaskQueueTool()

        this.ndItem.parent = null
        for (let index = 0; index < ItemNum; index++) {
            let item = this.ndCtn.children[index] || cc.instantiate(this.ndItem)
            !item.parent && this.ndCtn.addChild(item)

            this._oHeight = this._oHeight || item.height
            let halfNum = Math.ceil(ItemNum * 0.5)
            let unitPer = 1 / halfNum
            let itemHeight = (halfNum - Math.abs(index + 1 - halfNum)) * unitPer * this._oHeight
            this._itemHeights = this._itemHeights || []
            this._itemHeights[index] = itemHeight

            item.height = 0
            this._jumpOneItem(item, index, true)
        }
    }

    update(dt: number) {
        this.TaskQueueTool.doCmd()
    }

    /**
     * 跳动一个节点
     * @param item 要跳动的节点
     * @param index 序号
     * @param isFirstJump 是否第一次跳动
     */
    private _jumpOneItem(item: cc.Node, index: number, isFirstJump = false) {
        // cc.log(`${cc.js.getClassName(this)} _jumpOneItem`)

        this.TaskQueueTool.addCmd({
            cmd: Jump,
            params: {},
            call: (cmd, params) => {
                // cc.log(`${cc.js.getClassName(this)} Cmd.Jump params = `, params)

                let itemHeight = this._itemHeights[index]
                let curItemHeight = item.height
                let tarItemHeight = Math.random() * itemHeight
                let time = Math.abs(curItemHeight - tarItemHeight) / itemHeight * BaseJumpTime
                cc.tween(item)
                    .to(time, { height: tarItemHeight })
                    .call(() => {
                        this._jumpOneItem(item, index)
                    })
                    .start()

                this.TaskQueueTool.doneCmd(cmd)
            },
        }, !isFirstJump, false)
    }
}